<template>
  <div class="borrow-list">
    <div class="header">
      <h2>借阅记录</h2>
      <div class="header-actions">
        <el-button type="warning" @click="handleUpdateStatus" :icon="Refresh">更新状态</el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入用户名、真实姓名、图书名、作者、ISBN"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="借阅中" :value="1" />
            <el-option label="已归还" :value="2" />
            <el-option label="逾期" :value="3" />
            <el-option label="丢失" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 借阅记录列表 -->
    <el-table
      :data="borrowList"
      v-loading="loading"
      style="width: 100%"
      border
    >
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="phone" label="联系电话" width="130" />
      <el-table-column prop="isbn" label="ISBN" width="150" />
      <el-table-column prop="title" label="图书名称" min-width="200" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="publisher" label="出版社" width="150" />
      <el-table-column prop="borrowDate" label="借阅日期" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.borrowDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="returnDate" label="应还日期" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.returnDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="actualReturnDate" label="实际归还日期" width="160">
        <template #default="{ row }">
          {{ row.actualReturnDate ? formatDateTime(row.actualReturnDate) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button 
            v-if="row.status === 1" 
            size="small" 
            type="success" 
            @click="handleReturn(row)"
          >归还</el-button>
          <el-button 
            v-if="row.status === 1" 
            size="small" 
            type="warning" 
            @click="handleRenew(row)"
          >续借</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[5, 10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 归还图书对话框 -->
    <el-dialog
      v-model="returnDialog.visible"
      title="归还图书"
      width="400px"
    >
      <el-form
        ref="returnFormRef"
        :model="returnForm"
        label-width="100px"
      >
        <el-form-item label="图书名称">
          <span>{{ returnForm.bookTitle }}</span>
        </el-form-item>
        <el-form-item label="借阅人">
          <span>{{ returnForm.userName }}</span>
        </el-form-item>
        <el-form-item label="借阅日期">
          <span>{{ formatDateTime(returnForm.borrowDate) }}</span>
        </el-form-item>
        <el-form-item label="应还日期">
          <span>{{ formatDateTime(returnForm.returnDate) }}</span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="returnForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleReturnSubmit" :loading="returnDialog.loading">
            确定归还
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 续借图书对话框 -->
    <el-dialog
      v-model="renewDialog.visible"
      title="续借图书"
      width="400px"
    >
      <el-form
        ref="renewFormRef"
        :model="renewForm"
        :rules="renewRules"
        label-width="100px"
      >
        <el-form-item label="图书名称">
          <span>{{ renewForm.bookTitle }}</span>
        </el-form-item>
        <el-form-item label="借阅人">
          <span>{{ renewForm.userName }}</span>
        </el-form-item>
        <el-form-item label="原应还日期">
          <span>{{ formatDateTime(renewForm.returnDate) }}</span>
        </el-form-item>
        <el-form-item label="续借天数" prop="renewDays">
          <el-input-number v-model="renewForm.renewDays" :min="1" :max="30" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renewDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleRenewSubmit" :loading="renewDialog.loading">
            确定续借
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { 
  getBorrowList, 
  returnBook, 
  renewBook, 
  updateBorrowStatus
} from '@/api/borrow'
import { getUserList } from '@/api/user'
import { getBookList } from '@/api/book'

// 响应式数据
const loading = ref(false)
const borrowList = ref([])
const searchForm = reactive({
  keyword: '',
  status: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 归还对话框
const returnDialog = reactive({
  visible: false,
  loading: false
})

const returnForm = reactive({
  borrowId: null,
  bookTitle: '',
  userName: '',
  borrowDate: null,
  returnDate: null,
  remarks: ''
})

// 续借对话框
const renewDialog = reactive({
  visible: false,
  loading: false
})

const renewForm = reactive({
  borrowId: null,
  bookTitle: '',
  userName: '',
  returnDate: null,
  renewDays: 7
})

const renewRules = {
  renewDays: [{ required: true, message: '请输入续借天数', trigger: 'blur' }]
}

// 用户和图书选项
const userOptions = ref([])
const bookOptions = ref([])
const userLoading = ref(false)
const bookLoading = ref(false)

// 获取借阅记录列表
const fetchBorrowList = async () => {
  loading.value = true
  try {
    const response = await getBorrowList({
      page: pagination.current,
      size: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    if (response.code === 200) {
      borrowList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取借阅记录失败')
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchBorrowList()
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = null
  pagination.current = 1
  fetchBorrowList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchBorrowList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchBorrowList()
}

// 归还图书
const handleReturn = (row) => {
  returnForm.borrowId = row.id
  returnForm.bookTitle = row.title
  returnForm.userName = row.realName
  returnForm.borrowDate = row.borrowDate
  returnForm.returnDate = row.returnDate
  returnForm.remarks = ''
  returnDialog.visible = true
}

// 提交归还
const handleReturnSubmit = async () => {
  try {
    returnDialog.loading = true
    const response = await returnBook(returnForm.borrowId, returnForm.remarks)
    if (response.code === 200) {
      ElMessage.success('归还成功')
      returnDialog.visible = false
      fetchBorrowList()
    } else {
      ElMessage.error(response.message || '归还失败')
    }
  } catch (error) {
    console.error('归还失败:', error)
    ElMessage.error('归还失败')
  } finally {
    returnDialog.loading = false
  }
}

// 续借图书
const handleRenew = (row) => {
  renewForm.borrowId = row.id
  renewForm.bookTitle = row.title
  renewForm.userName = row.realName
  renewForm.returnDate = row.returnDate
  renewForm.renewDays = 7
  renewDialog.visible = true
}

// 提交续借
const handleRenewSubmit = async () => {
  try {
    renewDialog.loading = true
    const response = await renewBook(renewForm.borrowId, renewForm.renewDays)
    if (response.code === 200) {
      ElMessage.success('续借成功')
      renewDialog.visible = false
      fetchBorrowList()
    } else {
      ElMessage.error(response.message || '续借失败')
    }
  } catch (error) {
    console.error('续借失败:', error)
    ElMessage.error('续借失败')
  } finally {
    renewDialog.loading = false
  }
}

// 更新状态
const handleUpdateStatus = async () => {
  try {
    const response = await updateBorrowStatus()
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      fetchBorrowList()
    } else {
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'success',
    2: 'info',
    3: 'danger',
    4: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '借阅中',
    2: '已归还',
    3: '逾期',
    4: '丢失'
  }
  return statusMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  // 调试：检查token和登录状态
  console.log('当前token:', localStorage.getItem('token'))
  console.log('当前用户信息:', localStorage.getItem('userInfo'))
  
  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    return
  }
  
  fetchBorrowList()
})
</script>

<style scoped>
.borrow-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  padding: 0 20px;
  margin-bottom: 20px;
}

.el-table {
  flex: 1;
  margin: 0 20px;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 